"""
Generic code for plotting MeshGenC++ output in matplotlib.
Execute via

    $ python $MESHGENCPP/viz/python/plotmesh2.py

from an application directory.
"""

#----------------------------------------------------------
def plotmesh2(outputdir="mesh_output"):

    import os
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.tri as tri
    from helper2 import read_params
    from helper2 import read_tnode
    from helper2 import read_node
    from helper2 import read_bnd
    from helper2 import read_ghost
    from helper2 import read_area
    from helper2 import read_dual
    from helper2 import read_edge
    from helper2 import read_tedge
    from helper2 import read_eelem
    from helper2 import node_minmax

    # TITLE INFO --------------------------------------------------------------
    print ("")
    print ("   2D UNSTRUCTURED GRID PLOTTING ROUTINE")
    print ("")
    # END TITLE INFO ----------------------------------------------------------

    print (" Loading grid data: please wait ...")

    # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    # %%% READ-IN MESH INFO %%%
    # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    TF = os.path.exists(outputdir)
    if TF==False:
        print ("")
        print ("    Directory not found, outputdir = ",outputdir)
        print ("")
        exit()

    params = np.zeros(7, int)
    read_params(outputdir,params)
    NumElems      = params[0]
    NumPhysElems  = params[1]
    NumGhostElems = params[2]
    NumNodes      = params[3]
    NumPhysNodes  = params[4]
    NumBndNodes   = params[5]
    NumEdges      = params[6]

    tnode_full = np.zeros((NumElems,3),int)
    tnode = np.zeros((NumPhysElems,3),int)
    read_tnode(outputdir,params,tnode_full,tnode)

    x_full = np.zeros(NumNodes,float)
    y_full = np.zeros(NumNodes,float)
    x = np.zeros(NumPhysNodes,float)
    y = np.zeros(NumPhysNodes,float)
    read_node(outputdir,params,x_full,y_full,x,y)

    bnd = np.zeros(NumBndNodes,int)
    read_bnd(outputdir,params,bnd)
    x_bnd = np.zeros(NumBndNodes,float)
    y_bnd = np.zeros(NumBndNodes,float)
    for i in range(0,NumBndNodes):
        x_bnd[i] = x_full[bnd[i]]
        y_bnd[i] = y_full[bnd[i]]

    #read_ghost(outputdir,params)
    #read_area(outputdir,params)
    #read_dual(outputdir,params)
    #read_edge(outputdir,params)
    #read_tedge(outputdir,params)
    #read_eelem(outputdir,params)

    print (" Finished loading grid data.")
    print ("")

    # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    xminmax = np.zeros(4,float)
    node_minmax(NumNodes,x_full,y_full,xminmax)
    xmin = xminmax[0]
    xmax = xminmax[1]
    ymin = xminmax[2]
    ymax = xminmax[3]

    xtmp = 0.01*(xmax-xmin)
    ytmp = 0.01*(ymax-ymin)

    xmin = xmin - xtmp
    xmax = xmax + xtmp

    ymin = ymin - ytmp
    ymax = ymax + ytmp

    z = np.zeros(NumPhysElems,float)
    for i in range(0,NumPhysElems):
        z[i]=0.0

    z_full = np.zeros(NumElems,float)
    for i in range(0,NumElems):
        z_full[i]=0.0

    # CREATE PLOT OF PHYSICAL ELEMENTS
    plt.figure()
    plt.gca().set_aspect('equal')
    plt.gca().set_xlim([xmin,xmax])
    plt.gca().set_ylim([ymin,ymax])
    p1=plt.tripcolor(x, y, tnode, facecolors=z, edgecolors='k', cmap='RdPu')
    p1.set_clim([-1,1])
    plt.plot(x_bnd, y_bnd, 'ro')
    plt.title('Mesh Generated by MeshGenC++')
    #plt.savefig("meshgen_python_1.png", dpi=200, facecolor='w', edgecolor='w',
    #    orientation='portrait', papertype=None, format='png',
    #    transparent=False, bbox_inches=None, pad_inches=0.1)

    # CREATE PLOT OF PHYSICAL+GHOST ELEMENTS
    plt.figure()
    plt.gca().set_aspect('equal')
    plt.gca().set_xlim([xmin,xmax])
    plt.gca().set_ylim([ymin,ymax])
    p2=plt.tripcolor(x_full, y_full, tnode_full, facecolors=z_full, edgecolors='k', cmap='RdPu')
    p2.set_clim([-1,1])
    plt.plot(x_bnd, y_bnd, 'ro')
    plt.title('Mesh with Ghost Elements')
    #plt.savefig("meshgen_python_2.png", dpi=200, facecolor='w', edgecolor='w',
    #    orientation='portrait', papertype=None, format='png',
    #    transparent=False, bbox_inches=None, pad_inches=0.1)

    # SHOW PLOTS
    plt.show()

#----------------------------------------------------------


#----------------------------------------------------------
if __name__=='__main__':
    """
    If executed at command line prompt, simply call the function, with
    any argument used as setplot:
    """
    import sys
    args = sys.argv[1:]   # any command line arguments
    plotmesh2(*args)
#----------------------------------------------------------
